from ronglian_sms_sdk import SmsSDK
import logging
import os

logger = logging.getLogger('django')


class RongLianSms:
    """
    容联云通讯发送短信(单例模式)
    """
    DEFAULT_TID = '1'
    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        # 防止重复初始化
        if self._initialized:
            return
            
        # 从环境变量获取敏感配置信息，避免硬编码
        self.accId = os.getenv('RL_SMS_ACCID', '2c94811c9787a27f019855adc07b2bfd')
        self.accToken = os.getenv('RL_SMS_ACCTOKEN', '6c553cd984cb4e75967d665fdb59f453')
        self.appId = os.getenv('RL_SMS_APPID', '2c94811c9787a27f019855adc2222c04')
        self.sdk = SmsSDK(self.accId, self.accToken, self.appId)
        
        # 标记已完成初始化
        self.__class__._initialized = True

    def send_message(self, mobile, code, minute=5):
        """
        发送短信验证码

        Args:
            mobile (str): 手机号码
            code (str): 验证码
            minute (int): 有效时间（分钟），默认为5分钟

        Returns:
            dict: 短信发送结果
        """
        try:
            datas = (code, str(minute))
            resp = self.sdk.sendMessage(self.DEFAULT_TID, mobile, datas)
            logger.info(f"短信发送结果: {resp}")
            return resp
        except Exception as e:
            logger.error(f"短信发送失败: {e}")
            return {"statusCode": "-1", "errmsg": str(e)}